﻿// ********************************************************************************************************
// <copyright file="frmJoinExtData.cs" company="TopX Geo-ICT">
//     Copyright (c) 2012 TopX Geo-ICT. All rights reserved.
// </copyright>
// ********************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
// you may not use this file except in compliance with the License. You may obtain a copy of the License at 
// http:// www.mozilla.org/MPL/ 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF 
// ANY KIND, either express or implied. See the License for the specificlanguage governing rights and 
// limitations under the License. 
// 
// The Initial Developer of this version is Jeen de Vegt.
// 
// Contributor(s): (Open source contributors should list themselves and their modifications here). 
// Change Log: 
// Date           Changed By      Notes
// 29 March 2012  Jeen de Vegt    Inital coding
// ********************************************************************************************************
namespace TableEditorNew.Forms
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Windows.Forms;
    using TableEditorNew.BO;
    using TableEditorNew.Utils;
    using TableEditorNew.utils;

    /// <summary>
    ///  Form-class for joining with external data
    /// </summary>
    public partial class frmJoinExtData : Form
    {
        /// <summary>Filter for the filetypes to import from</summary>
        private const string OpenFileFilter = "Excel Files (*.xls)|*.xls|CSV Files (*.csv)|*.csv|All Files|*.*";
      //  private const string OpenFileFilter = "Excel Files (*.xls)|*.xls|Open Office Files (*.ods)|*.ods|CSV Files (*.csv)|*.csv|All Files|*.*";

        /// <summary>The shapedata</summary>
        private DataTable shapeData;

        /// <summary>Initializes a new instance of the frmJoinExtData class</summary>
        /// <param name = "dt">The datatable.</param>
        public frmJoinExtData(DataTable dt)
        {
            InitializeComponent();

            this.shapeData = dt;

            this.FillCurrentKeyColumns(dt);
        }

        /// <summary>Fill combobox with fields from shape</summary>
        /// <param name = "dt">The datatable.</param>
        private void FillCurrentKeyColumns(DataTable dt)
        {
            cboCurrentKeyCol.DataSource = BOShapeData.GetVisibleFieldNames(dt);
        }

        /// <summary>Select file to import from</summary>
        /// <param name = "sender">The sender of the event.</param>
        /// <param name = "e">The arguments.</param>
        private void btnInputFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = OpenFileFilter;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtInputFile.Text = ofd.FileName;
            }
        }

        /// <summary>Fill combobox with workbooks</summary>
        private void FillWorkBooks()
        {
            // Get workbooks
            List<string> books = XLSImport.GetWorkbooks(txtInputFile.Text);

            cboWorkBooks.DataSource = books;
        }

        /// <summary>Fill combobox with fields from external data</summary>
        /// <param name = "sender">The sender of the event.</param>
        /// <param name = "e">The arguments.</param>
        private void cboWorkBooks_SelectedIndexChanged(object sender, EventArgs e)
        {
            //List<string> colNames = XLSImport.GetColumnNames(txtInputFile.Text, cboWorkBooks.SelectedItem.ToString());

            //cboExternalKeyCol.DataSource = colNames;
        }

        /// <summary>Import the data</summary>
        /// <param name = "sender">The sender of the event.</param>
        /// <param name = "e">The arguments.</param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (cboExternalKeyCol.SelectedItem == null || cboExternalKeyCol.SelectedItem.ToString() == string.Empty)
            {
                MessageBox.Show("Please select key columns.");
            }
            else
            {
                bool importSuccess = this.ImportData();
            
                if (importSuccess)
                {
                    this.Close();
                }
            }
        }

        /// <summary>Import the data</summary>
        /// <returns>Value indicating if importing was successfull</returns>
        private bool ImportData()
        {
            DataTable importedData;

            // csv of excel

            bool retVal = true;

            if (cboWorkBooks.Visible)
            {
                importedData = XLSImport.GetData(txtInputFile.Text, cboWorkBooks.SelectedItem.ToString());
            }
            else
            {
                importedData = CSVImport.GetData(txtInputFile.Text, cboDelimiter.Text.ToString());
            }

            if ((importedData.Rows.Count - 1) != this.shapeData.Rows.Count)
            {
                MessageBox.Show("Amount of rows does not match.");

                retVal = false;
            }
            else
            {
                for (int i = 0; i < importedData.Columns.Count; i++)
                {
                    DataColumn dc = importedData.Columns[i];

                    // to be changed in next version? Set length default to 50
                    BOShapeData.AddDataColumn(this.shapeData, importedData.Rows[0][i].ToString(), "String", "0", 50);
                }

                for (int i = 0; i < this.shapeData.Rows.Count; i++)
                {
                    string currentKeyValue = this.shapeData.Rows[i][cboCurrentKeyCol.SelectedItem.ToString()].ToString();

                    string searchString = string.Format("{0} = '{1}'", cboExternalKeyCol.SelectedItem.ToString(), currentKeyValue);
                    DataRow[] rows = importedData.Select(searchString);

                    for (int j = 0; j < importedData.Columns.Count; j++)
                    {
                        this.shapeData.Rows[i][importedData.Columns[j].ColumnName] = rows[0][importedData.Columns[j].ColumnName].ToString();
                    }
                }
            }

            return retVal;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            lblWorkbook.Visible = false;
            cboWorkBooks.Visible = false;
            lblDelimiter.Visible = false;
            cboDelimiter.Visible = false;
            btnGetColumns.Visible = false;
            groupBox1.Enabled = false;

            if (!File.Exists(txtInputFile.Text))
            {
                MessageBox.Show("File does not exist.");
            }
            else
            {
              //  groupBox1.Enabled = true;
                btnGetColumns.Visible = true;

                string extension = Path.GetExtension(txtInputFile.Text);
                //if (extension == ".xls" || extension == ".ods")
                if (extension == ".xls")
                {
                    lblWorkbook.Visible = true;
                    cboWorkBooks.Visible = true;

                    this.FillWorkBooks();
                }
                else if (extension == ".csv")
                {
                    lblDelimiter.Visible = true;
                    cboDelimiter.Visible = true;


                }
                else
                {
                   // groupBox1.Enabled = false;
                    btnGetColumns.Visible = false;
                    MessageBox.Show("Filetype not supported.");
                }
            }     
        }

        private void btnGetColumns_Click(object sender, EventArgs e)
        {
            if (cboWorkBooks.Visible == true)
            {
                List<string> colNames = XLSImport.GetColumnNames(txtInputFile.Text, cboWorkBooks.SelectedItem.ToString());

                cboExternalKeyCol.DataSource = colNames;

                groupBox1.Enabled = true;
            }
            else
            {
                if (cboDelimiter.Text.ToString() == string.Empty)
                {
                    MessageBox.Show("No delimiter selected.");
                }
                else
                {
                    List<string> colNames = CSVImport.GetColumnNames(txtInputFile.Text, cboDelimiter.Text.ToString());

                    cboExternalKeyCol.DataSource = colNames;

                    groupBox1.Enabled = true;
                }
            }

            

            

            // Lees eerste regel van bestand in voor de kolomnamen

            //List<string> colNames = XLSImport.GetColumnNames(txtInputFile.Text, cboWorkBooks.SelectedItem.ToString());

            //cboExternalKeyCol.DataSource = colNames;
        }
    }
}
